import { ref, type Ref } from "vue";
import { defineStore } from "pinia";
import * as signalR from "@microsoft/signalr";
import signalEvent from "@/utils/signalEvent";
import { useTabsStore } from "@/store/modules/tabs";

export const useSignalrStore = defineStore("signalR", () => {
  const connection: Ref<signalR.HubConnection | null> = ref(null);
  const signalRInit = () => {
    connection.value = new signalR.HubConnectionBuilder()
      .withUrl(import.meta.env.VITE_API_URL + "/api/chatHub", {
        withCredentials: false, // 跨域请求时不携带凭证
        skipNegotiation: true, // 跳过协商，直接使用WebSockets
        transport: signalR.HttpTransportType.WebSockets // 使用WebSockets传输
      })
      .configureLogging(signalR.LogLevel.Information)
      .build();
    startConnection(); // 连接服务

    // connection.value.onclose(() => {
    //   startConnection();
    // });
  };

  const startConnection = async () => {
    try {
      connection.value?.start();
      initEvent(); // 初始化事件
    } catch (err) {
      setTimeout(() => startConnection(), 5000);
      console.error(err);
    }
  };
  /**
   * @description: 全局消息接收事件
   * @return {*}
   */
  const initEvent = () => {
    connection.value?.on("DataEvent", (moduleName, dataName, data) => {
      // console.log(moduleName, dataName, data);
      signalEvent.$emit(moduleName, { dataName, data });
    });
    connection.value?.on("MessageEvent", (moduleName, data) => {
      console.log(moduleName, data);
      signalEvent.$emit(moduleName, { data });
    });
    // 通用消息提示
    connection.value?.on("CommonMessageEvent", (moduleName, data) => {
      signalEvent.$emit("CommonMessageEvent", { dataName: moduleName, data });
    })
    // 测试消息
    connection.value?.on("TestMessageEvent", (taskId, data) => {
      console.log(taskId, data);
      signalEvent.$emit(taskId, { dataName: "TestMessageEvent", data });
    });
    // 测试弹窗消息
    connection.value?.on("TestDialogEvent", (taskId, data) => {
      console.log(taskId, data);
      signalEvent.$emit(taskId, { dataName: "TestDialogEvent", data });
    });
    connection.value?.on("TestDataEvent", (taskId, dataName, data) => {
      console.log(taskId, dataName, data);
      useTabsStore().testTaskId = taskId || "";
      signalEvent.$emit(taskId, { dataName, data });
    });
    // 校准消息
    connection.value?.on("CalibrationDataEvent", (calibrationName, dataName, data) => {
      console.log(calibrationName, dataName, data);
      signalEvent.$emit(calibrationName, { dataName, data });
    });
  };
  return { connection, signalRInit, initEvent };
});
